package com.liliya.servlet.cate;

import com.liliya.pojo.Cate;
import com.liliya.service.CateService;
import com.liliya.service.impl.CateServiceImpl;
import com.liliya.utils.UploadFileUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @Description TODO
 * @Author hhy
 * @Date 2021/1/9 18:33
 */
@WebServlet(urlPatterns = "/cate/update")
public class CateUpdateServlet extends HttpServlet {
    CateService cateService = new CateServiceImpl();


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        CateService cateService = new CateServiceImpl();
        int num = 1;
        int total = cateService.totalCate();
        String p = req.getParameter("p");
        if (p != null) {
            num = Integer.parseInt(p);
        }
        Cate cate = cateService.findCateByRow(num);
        int pre = num - 1 < 1 ? 1 : num - 1;
        int next = num + 1 > total ? total : num + 1;
        req.setAttribute("cate",cate);
        req.setAttribute("pre",pre);
        req.setAttribute("next",next);
        req.setAttribute("total",total);

        req.getRequestDispatcher("./cate.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //字段名字
        String cateName = "", cateDes = "", cateStyle = "",cateNum = "";
        //文件名
        String fileName = "";
        if (!ServletFileUpload.isMultipartContent(req)) {
            return;
        }
        String cateFilePath = "/upload/cate/";
        String uploadPath = this.getServletContext().getRealPath(cateFilePath);

        File uploadFile = new File(uploadPath);
        if (!uploadFile.exists()) {
            uploadFile.mkdir();
        }

        //缓存  -- 临时文件：如果文件超过了预期的大小，那就把这个文件放到临时文件中华，过几天再删除
        String temPath = this.getServletContext().getRealPath("/WEB-INF/tem");
        System.out.println(uploadPath);
        File temFile = new File(temPath);
        if (!temFile.exists()) {
            temFile.mkdir();
        }

        //1. 创建 DiskFileItemFactory 用于限制文件大小之类的参数，如果不写的话，那就是默认值了
        DiskFileItemFactory factory = UploadFileUtil.getDiskFileItemFactory(temFile);

        //2. 获取ServletFileUpload
        ServletFileUpload upload = UploadFileUtil.getServletFileUpload(factory);

        //3. 把前端的请求封装成一个FileItem对象 （每一个表单对象）
        try {
            List<FileItem> fileItems = upload.parseRequest(req);
            for (FileItem fileItem : fileItems) {
                if (fileItem.isFormField()) {//如果这个是普通的表单就正常的流程
                    String inputName = fileItem.getFieldName();
                    if (inputName.equals("catename")){
                        cateName = fileItem.getString("utf-8");
                        System.out.println("----》"+cateName);
                    }else if (inputName.equals("catedes")){
                        cateDes = fileItem.getString("utf-8");
                        System.out.println("----》"+cateDes);
                    }else if (inputName.equals("catenum")){
                        cateNum = fileItem.getString("utf-8");
                        System.out.println("----》"+cateNum);
                    }else if (inputName.equals("catestyle")){
                        cateStyle = fileItem.getString("utf-8");
                        System.out.println("----》"+cateStyle);
                    }

//                    System.out.println("表单字段的name："+fileItem.getFieldName());
//                    System.out.println("表单字段的value"+fileItem.getString("utf-8"));

                } else {//文件
                    //处理文件
                    String uploadFileName = fileItem.getName();
                    if (uploadFileName.trim().equals("") || uploadFileName == null) { //文件名不合法
                        continue;
                    }

                    //获取上传的文件名
                    fileName = uploadFileName.substring(uploadFileName.lastIndexOf("/") + 1);
                    String dateTime = new SimpleDateFormat("YYMMddHHmmssSSSS").format(System.currentTimeMillis());
                    fileName = dateTime + "_" + fileName;

                    //文件写入
                    fileItem.write(new File(uploadPath + "/" + fileName));
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }


        Cate cate = cateService.findCateByNum(Integer.parseInt(cateNum));
        if (!cateName.isEmpty()){
            cate.setCatename(cateName);
        }
        if (!cateDes.isEmpty()){
            cate.setCatedes(cateDes);
        }
        if (!cateStyle.isEmpty()){
            cate.setCatestyle(cateStyle);
        }
        if (!fileName.isEmpty()) {
            cate.setCateimglink(cateFilePath + fileName);
        }
        cateService.updateCate(cate);

//        resp.sendRedirect(req.getContextPath() + cateFilePath + fileName);
        resp.sendRedirect(req.getContextPath() + "/cate/update");
    }

}

